﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Globalization;

namespace MSL.DataBase.Lib
{
    /// <summary>
    /// 连接配置
    /// </summary>
    public static class DBConfig
    {
        /// <summary>SqlClient</summary>
        public const string SqlClient = "System.Data.SqlClient";
        /// <summary>OleDb</summary>
        public const string OleDb = "System.Data.OleDb";
        /// <summary>OracleClient</summary>
        public const string OracleClient = "System.Data.OracleClient";
        /// <summary>MySQL</summary>
        public const string MySQL = "MySql.Data.MySqlClient";
        /// <summary>SQLite</summary>
        public const string SQLite = "System.Data.SQLite";
        /// <summary>SQLite</summary>
        public const string Txt = "";

        #region 私有变量
        private static object _locker = new Object();
        private static int _maxPool = 1;                       //数据库连接池最大打开数
        private static int _minPool = 1;                       //数据库连接最小打开数
        private static string _dbHelperClass = "MSL.DataBase.Core.SqlHelper";//数据库处理类名
        private static string _serverName = String.Empty;      //服务器名称
        private static string _connString = String.Empty;      //数据库链接
        private static string _dbName = String.Empty;          //连接的数据库名称
        private static bool _trustLink = true;                 //是否为信任连接
        private static string _userName = String.Empty;        //用户名
        private static string _passWord = String.Empty;        //用户密码
        private static bool _isWriteLog = true;                //是否记录日志
        private static string _logPath = String.Empty;         //日志保存路径
        private static string _providerName = String.Empty;    //
        private static DataBaseType _dataBaseType = DataBaseType.Sql;// 数据库类别 由程序集动态识别
        #endregion

        #region 属性

        /// <summary>
        /// 
        /// </summary>
        public static string ProviderName
        {
            get { return _providerName; }
            set { _providerName = value; }
        }

        /// <summary>
        /// 数据库类型
        /// </summary>
        public static DataBaseType DataBaseType
        {
            get { return _dataBaseType; }
            set { _dataBaseType = value; }
        }
        /// <summary>
        /// 用户名
        /// </summary>
        public static string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
        /// <summary>
        /// 用户密码
        /// </summary>
        public static string PassWord
        {
            get { return _passWord; }
            set { _passWord = value; }
        }
        /// <summary>
        /// 服务器名称
        /// </summary>
        public static string ServerName
        {
            get { return _serverName; }
            set { _serverName = value; }
        }
        /// <summary>
        /// 数据库链接
        /// </summary>
        public static string ConnString
        {
            get
            {
                if (!String.IsNullOrEmpty(_connString))
                {
                    return _connString;
                }
                try
                {
                    return MSL.DataBase.Lib.Config.GetProviderApp("ConnectionString", out _providerName);
                }
                catch (Exception er)
                {
                    new Exception("Error on WriteLog (配置项不存在):" + er);
                    return null;
                }
            }
            set
            {
                _connString = value;
                _dbHelperClass = GetHelperClass(_providerName);
            }
        }

        /// <summary>
        /// 日志保存绝对路径 
        /// </summary>
        public static string LogPath
        {
            get
            {
                if (!String.IsNullOrEmpty(_logPath))
                {
                    return _logPath;
                }
                try
                {
                    return MSL.DataBase.Lib.Config.GetApp("LogPath");
                }
                catch (Exception er)
                {
                    new Exception("Error on WriteLog (配置项不存在):" + er);
                    return null;
                }
            }
            set { _logPath = value; }
        }
        /// <summary>
        /// 是否记录日志
        /// </summary>
        public static bool IsWriteLog
        {
            get
            {
                if (!_isWriteLog)
                {
                    Boolean.TryParse(MSL.DataBase.Lib.Config.GetApp("IsWriteLog"), out _isWriteLog);
                }
                return _isWriteLog;
            }
            set { _isWriteLog = value; }
        }
        /// <summary>
        /// 数据库连接池最大打开数
        /// </summary>
        public static int MaxPool
        {
            get { return _maxPool; }
            set { _maxPool = value; }
        }
        /// <summary>
        /// 数据库连接最小打开数
        /// </summary>
        public static int MinPool
        {
            get { return _minPool; }
            set { _minPool = value; }
        }

        /// <summary>
        /// 数据库处理类名
        /// </summary>
        public static string DbHelperClass
        {
            get { return _dbHelperClass; }
            set { _dbHelperClass = value; }
        }

        #endregion

        #region 其它方法

        #region 获得数据库处理类

        /// <summary>
        /// 获得数据库处理类
        /// </summary>
        /// <returns></returns>
        public static string GetHelperClass(string providerName)
        {
            string dbClass = String.Empty;
            switch (providerName)
            {
                case SqlClient: dbClass = "MSL.DataBase.Core.SQLHelper"; break;
                case OleDb: dbClass = "MSL.DataBase.Core.OleHelper"; break;
                case OracleClient: dbClass = "MSL.DataBase.Core.OracleHelper"; break;
                case MySQL: dbClass = "MSL.DataBase.Core.MySqlHelper"; break;
                case SQLite: dbClass = "MSL.DataBase.Core.SQLiteHelper"; break;
                default: dbClass = "MSL.DataBase.Core.SQLHelper"; break;
            }
            return dbClass;
        }
        #endregion

        /// <summary>
        /// 获得数据库提供者
        /// </summary>
        /// <param name="connString">数据库链接</param>
        /// <returns></returns>
        public static string GetPovider(string connString)
        {
            if (String.IsNullOrEmpty(connString))
            {
                connString = _connString;
            }
            connString = connString.ToLower();
            if (connString.Contains("microsoft.jet.oledb.4.0"))
            {
                return OleDb;
            }
            else if (connString.Contains("provider=msdaora") || connString.Contains("provider=oraoledb.oracle") || connString.Contains("description"))
            {
                return OracleClient;
            }
            else if (connString.Contains("host="))
            {
                return MySQL;
            }
            else if (connString.Contains("failifmissing="))
            {
                return SQLite;
            }
            else
            {
                return SqlClient;
            }
        }

        #endregion

        #region 获得各种数据库连接

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataBaseType">数据库类型</param>
        /// <returns></returns>
        public static string GetConnectionString(DataBaseType dataBaseType)
        {
            string result = String.Empty;
            switch (dataBaseType)
            {
                case DataBaseType.Sql:
                    if (_trustLink)
                    {
                        result = String.Format("Server={0};Database={1};Integrated Security=True", _serverName, _dbName);
                    }
                    else
                    {
                        result = String.Format("Server={0};Database={1};Uid={2};Pwd={3};", _serverName, _dbName, _userName, _passWord);
                    }
                    break;
                case DataBaseType.Oracle:
                    result = String.Format("Data Source={0};Persist Security Info=no;User ID={1};_passWord={2}", _serverName, _userName, _passWord);
                    break;
                case DataBaseType.MySql:
                    result = String.Format("server={0};uid={1};_passWord={2};database={3};pooling=false", _serverName, _userName, _passWord, _dbName);
                    break;
                case DataBaseType.Access:
                    result = GetOleDbConnection(DataBaseType.Access, _dbName, _userName, _passWord, _serverName, _trustLink);
                    break;
                default:
                    result = GetOleDbConnection(DataBaseType.Access, _dbName, _userName, _passWord, _serverName, _trustLink);
                    break;
            }
            return result;
        }

        /// <summary>
        /// 获得数据库连接
        /// </summary>
        /// <param name="dataBaseType">数据库类别</param>
        /// <param name="dataBase">数据库名,如果是Access默认地址为~/App_Data/</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <param name="workstation">主机</param>
        /// <param name="trustLink">信任的连接</param>
        /// <returns>是否连接成功</returns>
        public static string GetOleDbConnection(DataBaseType dataBaseType, string dataBase, string userName, string passWord, string workstation, bool trustLink)
        {
            string result = String.Empty;
            switch (dataBaseType)
            {
                case DataBaseType.Access:
                    if (dataBase.IndexOf(":") < 0)
                    {
                        dataBase = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/") + dataBase;
                    }
                    result = String.Format(CultureInfo.CurrentCulture, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\";User Id={1};jet OleDB:Database PassWord={2}", dataBase, userName, passWord);
                    break;
                case DataBaseType.Sql:
                    // 信任的连接与不信任的连接的差距
                    if (trustLink)
                    {
                        result = String.Format(CultureInfo.CurrentCulture, "Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};Integrated Security=SSPI;Max Pool Size={2}; Min Pool Size={3}", workstation, dataBase, _maxPool, _minPool);
                    }
                    else
                    {
                        result = String.Format(CultureInfo.CurrentCulture, "Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};PassWord={3};Max Pool Size={4}; Min Pool Size={5}", workstation, dataBase, userName, passWord, _maxPool, _minPool);
                    }
                    break;
                case DataBaseType.Oracle:
                    if (!trustLink)
                    {
                        // 需要上传文件时必须用 Provider=OraOLEDB.Oracle.1
                        result = String.Format(CultureInfo.CurrentCulture, "Provider=OraOLEDB.Oracle.1;Data Source={0};User Id={1};PassWord={2};", dataBase, userName, passWord);
                    }
                    break;
            }
            return result;
        }

        #endregion
    }
}
